<?php
final class ABMain{
	const version = '0.1 Alpha';
	function __construct(){
		throw new ABException('ABMain is static class can\'t create intance');
	}

/**
 * Permite iniciar y enrutar las peticiones
 */
	static function init(){
		$a_request = self::parse($_GET['url']);
		extract($a_request);
		//var_dump($a_request);
		$module  = !empty($module)? $module.'/': '';
		$s_file = PATH_CORE.'/controller/'. $module.$control.'.php';
		if(is_file($s_file)){
			require $s_file;
			//nombre del template 
			$s_tpl = empty($module)?$control:$module;
			$s_instance = $control .'Controller';
			if(!class_exists ($s_instance, false))
				throw new ABException("No exist controller <strong>$control</strong>");
			$o_tpl = new ABView($s_tpl, $action);
			$o_controller = new $s_instance($o_tpl);
			if(!($o_controller instanceof ABController))
				throw new ABException("<strong>$control</strong> should be instance of ABController");
			if(!method_exists($o_controller, $action))
				throw new ABException("No exist action <strong>$action</strong> in controller <strong>$control</strong>");
			call_user_func_array(array($o_controller , $action), $param);
		}else{
			throw new ABException("No exist file controller <strong>$control</strong> as <em>$s_file</em>");
		}
	}

	static function parse($s_str){
		$a_clean = array( '\\', '..','//');
		$s_str = str_replace($a_clean,  '', $s_str);
		$a_args = explode('/', $s_str);
		if(count($a_args) == 1 and empty($a_args[0])){
			$s_module = '';
			$s_control= 'default';
			$s_action = 'index';
		}else{
			$s_control = array_shift($a_args);
			//si no existe el controller toma el primer parametro como modulo
			$s_module = is_file(PATH_CORE."/controller/$s_control.php") ? '':$s_control;
			//si existe modulo toma el segundo parametro como controller
			$s_control = !empty($s_module)? array_shift($a_args): $s_control;
			/* si el control no existe toma usa el controller 'default'*/
			$s_control = (!empty($s_module) and !is_file(PATH_CORE."controller/$s_module/$s_control.php"))?
				'default' : $s_control;
			/*Busco la accion*/
			$s_action = array_shift($a_args);
			//si no hay accion toma por defecto index
			$s_action  = empty($s_action)? 'index': $s_action;
		}
		//el resto son parametros de la accion
		$a_args = array_map(array('ABApi', 'filterParam'),$a_args);
		return array('module'=> $s_module, 'control' => $s_control,
			'action' => $s_action, 'param' => $a_args);
	}
	
}
?>
